/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest.front;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.bo.req.*;
import me.zhengjie.modules.system.bo.resp.QztySetUpIndexResp;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.util.IPUtils;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @website https://eladmin.vip
* @author cjl
* @date 2023-05-16
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "DCC商品相关管理")
@RequestMapping("/front/setup")
public class FrontShangPingController {




    private final DccShangpinService dccShangpinService;

    private final DccShangpinDhjlService dccShangpinDhjlService;

    private final DccDizhiService dccDizhiService;
    private final RedisUtils redisUtils;
    private final DccUserService dccUserService;
    private final DccJifenService dccJifenService;






    @Log("商品兑换")
    @ApiOperation("商品兑换")
    @AnonymousAccess
    @PostMapping(value = "/trans")
    public ResponseEntity<Object> index(@RequestBody DuiHuanReq duiHuanReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        String loginIdAsString = StpUtil.getLoginIdAsString();
        if (!StringUtils.isAllEmpty(loginIdAsString)){
            DccUserDto user = (DccUserDto) StpUtil.getSession().get("user");

            //获取商品
            DccShangpinDto dccShangpinServiceById = dccShangpinService.findById(duiHuanReq.getComId());
            DccDizhiDto dccDizhiServiceById = dccDizhiService.findById(duiHuanReq.getAddressId());
            if (dccDizhiServiceById==null){
                return new ResponseEntity<>("地址信息不符合要求，请重新选择地址",HttpStatus.BAD_GATEWAY);
            }
            //判断商品是否足够
            if (dccShangpinServiceById==null||dccShangpinServiceById.getStatus().equals(0)){
                return new ResponseEntity<>("商品已下架",HttpStatus.BAD_GATEWAY);
            }
            if (dccShangpinServiceById.getTotal()<=0){
                return new ResponseEntity<>("商品不足",HttpStatus.BAD_GATEWAY);
            }
            //判断积分是否足够
            int i = Integer.parseInt(user.getGroupid());
            if (i<dccShangpinServiceById.getJifen()){
                return new ResponseEntity<>("积分不足",HttpStatus.BAD_GATEWAY);
            }
            String key1="duihua"+loginIdAsString;
            String key2="duihuasp"+dccShangpinServiceById.getId();

            try {
                boolean b = redisUtils.hasKey(key1);
                if (b){
                    return new ResponseEntity<>("此时系统兑换人数太多，请稍后兑换",HttpStatus.BAD_GATEWAY);
                }
                redisUtils.set(key1,loginIdAsString,15, TimeUnit.SECONDS);
                int i1 = i - dccShangpinServiceById.getJifen();
                user.setGroupid(i1+"");
                StpUtil.getSession().set("user",user);
                DccUser dccUser=new DccUser();
                BeanUtil.copyProperties(user,dccUser);
                dccUserService.update(dccUser);
                boolean b1 = redisUtils.hasKey(key2);
                if (b1){
                    return new ResponseEntity<>("此时系统兑换人数太多，请稍后兑换.",HttpStatus.BAD_GATEWAY);
                }
                redisUtils.set(key2,dccShangpinServiceById.getId(),15, TimeUnit.SECONDS);
                int i2 = dccShangpinServiceById.getTotal() - 1;

                dccShangpinServiceById.setTotal(i2);
                DccShangpin dccShangpin=new DccShangpin();
                BeanUtil.copyProperties(dccShangpinServiceById,dccShangpin);
                if (i2==0){
                    dccShangpin.setStatus(2);
                }
                dccShangpin.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
                dccShangpinService.update(dccShangpin);
                DccShangpinDhjl dccShangpinDhjl=new DccShangpinDhjl();
                dccShangpinDhjl.setComId(dccShangpinServiceById.getId()+"");
                dccShangpinDhjl.setJifen(dccShangpinServiceById.getJifen());
                dccShangpinDhjl.setStatus(1);
                dccShangpinDhjl.setUid(loginIdAsString);
                dccShangpinDhjl.setCreatedAt(new Timestamp(System.currentTimeMillis()));
                dccShangpinDhjl.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
                dccShangpinDhjl.setTitle(dccShangpinServiceById.getDccTitle());
                DccShangpinDhjlDto dccShangpinDhjlDto = dccShangpinDhjlService.create(dccShangpinDhjl);

                DccJifen dccJifen=new DccJifen();
                dccJifen.setUid(StpUtil.getLoginIdAsString());
                dccJifen.setPoint(i1);
                dccJifen.setCommonId(dccShangpinDhjlDto.getId());
                dccJifen.setText("积分兑换，兑换了"+dccShangpinServiceById.getDccTitle());
                dccJifen.setType(1);
                dccJifen.setStatus(1);
                dccJifen.setCreatedAt(new Timestamp(System.currentTimeMillis()));
                dccJifen.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
                dccJifenService.create(dccJifen);

            }catch (Exception e){
                e.printStackTrace();
                return new ResponseEntity<>("兑换失败",HttpStatus.BAD_GATEWAY);
            }
            return new ResponseEntity<>("兑换成功",HttpStatus.OK);
        }else {
            return new ResponseEntity<>("请先登录",HttpStatus.UNAUTHORIZED);

        }


    }


    @Log("商品列表")
    @ApiOperation("商品列表")
    @AnonymousAccess
    @PostMapping(value = "/sp/list")
    public ResponseEntity<Object> list(@RequestBody QueryBaseReq queryBaseReq){
        DccShangpinQueryCriteria criteria =new DccShangpinQueryCriteria();
        Sort sort =Sort.by(Sort.Direction.DESC,"updatedAt");
        Pageable pageable =PageRequest.of(queryBaseReq.getPage()-1, queryBaseReq.getSize(),sort);
        Map<String, Object> stringObjectMap = dccShangpinService.queryAll(criteria, pageable);
        return new ResponseEntity<>(stringObjectMap,HttpStatus.OK);
    }





    @Log("商品兑换记录")
    @ApiOperation("商品兑换记录")
    @AnonymousAccess
    @PostMapping(value = "/dhjl/daka")
    public ResponseEntity<Object> daka(@RequestBody QueryBaseReq queryBaseReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }
        DccShangpinDhjlQueryCriteria criteria =new DccShangpinDhjlQueryCriteria();
        criteria.setUid(StpUtil.getLoginIdAsString());
        Sort sort =Sort.by(Sort.Direction.DESC,"updatedAt");
        Pageable pageable =PageRequest.of(queryBaseReq.getPage()-1, queryBaseReq.getSize(),sort);
        Map<String, Object> stringObjectMap = dccShangpinDhjlService.queryAll(criteria, pageable);
        return new ResponseEntity<>(stringObjectMap,HttpStatus.OK);
    }






}